package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.ProcessContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.WorkDistribute;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  任务分配详情
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/5/12 15:03
 */
public class WorkDistributeDetailFrament extends BaseFragment {
  protected static final String EXTRA_CONTENT =
      WorkDistributeListActivity.class.getSimpleName() + "EXTRA_CONTENT";
  protected static final String EXTRA_PROCESSCONTENT =
      WorkDistributeListActivity.class.getSimpleName() + "EXTRA_PROCESSCONTENT";
  @BindView(R.id.tv_executor) TextView tvExecutor;
  @BindView(R.id.tv_appointer) TextView tvAppointer;
  //@BindView(R.id.tv_planClass_workProcess) TextView tvPlanClassWorkProcess;
  @BindView(R.id.tv_planClass) TextView tvPlanClass;
  @BindView(R.id.tv_requestTime) TextView tvRequestTime;
  @BindView(R.id.tv_planContent) TextView tvPlanContent;
  @BindView(R.id.et_planContentDesc) EditText etPlanContentDesc;
  @BindView(R.id.tv_planEsteTime) TextView tvPlanEsteTime;
  @BindView(R.id.tv_executor_distribute) TextView tvExecutorDistribute;
  @BindView(R.id.tv_corporator) TextView tvCorporator;
  @BindView(R.id.et_remark) EditText etRemark;
  @BindView(R.id.tv_appointer_distribute) TextView tvAppointerDistribute;
  @BindView(R.id.tv_planKind) TextView tvPlanKind;
  @BindView(R.id.tv_applicant) TextView tvApplicant;
  @BindView(R.id.tv_status) TextView tvStatus;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;

  private final int REQUETS_TIME = 0;
  private final int REQUETS_EXCMAN = 1;
  private final int REQUETS_COOPMAN = 2;
  private final int REQUETS_DELETE = 3;
  private WorkDistribute content;
  private ProcessContent processContent;
  private CurrentUser mUser;
  private String id;
  private String excManId;
  private String excManName;
  private String coopManIds;
  private String coopManNames;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom("任务分配详情");
    content = (WorkDistribute) getArguments().get(EXTRA_CONTENT);
    processContent = (ProcessContent) getArguments().getSerializable(EXTRA_PROCESSCONTENT);
    mUser = CurrentUser.newInstance(getActivity());
    if (content == null) {
      id = UUID.randomUUID().toString();
      excManId = "";
      excManName = "";
      coopManIds = "";
      coopManNames = "";
    } else {
      id = content.getId();
      excManId = content.getExcManId();
      excManName = content.getExcManName();
      coopManIds = content.getCoopManIds();
      coopManNames = content.getCoopManNames();
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_save_delete, menu);
    if (content == null) {
      //添加: 只可以保存
      menu.getItem(1).setVisible(false);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_work_distribute, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    tvExecutor.setText(processContent.getExcManName());
    tvAppointer.setText(processContent.getTaskManName());
    tvPlanClass.setText(processContent.getPlanKindName());
    tvRequestTime.setText(processContent.getPlanEsteTime());
    tvPlanContent.setText(processContent.getPlanContentDesc());
    tvAppointerDistribute.setText(mUser.getRealName());
    tvPlanKind.setText(processContent.getPlanKindType());
    tvApplicant.setText(mUser.getRealName());
    tvStatus.setText("审核发布");
    tvRegStaffName.setText(mUser.getRealName());
    tvRegDate.setText(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));

    if (content != null) {
      etPlanContentDesc.setText(content.getPlanContentDesc());
      tvPlanEsteTime.setText(content.getPlanEsteTime());
      tvExecutorDistribute.setText(content.getExcManName());
      tvCorporator.setText(content.getCoopManNames());
      etRemark.setText(content.getRemark());
      tvRegStaffName.setText(content.getRegStaffName());
      tvRegDate.setText(content.getRegDate());
      tvStatus.setText(content.getPlanStatusName());
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //添加
        if (isComplete()) {
          volleyPostSave();
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUETS_DELETE);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private boolean isComplete() {
    if (TextUtils.isEmpty(etPlanContentDesc.getText().toString()) || TextUtils.isEmpty(
        tvExecutorDistribute.getText().toString()) || TextUtils.isEmpty(
        tvPlanEsteTime.getText().toString())) {
      ToastUtil.show(R.string.complete_hint);
      return false;
    } else {
      return true;
    }
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_WORK_DISTRIBUTR_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", content.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_WORK_DISTRIBUTR_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", id);//任务主键id
    params.put("planSourceId", processContent.getId());//任务来源id
    params.put("planContentDesc", etPlanContentDesc.getText().toString());//计划任务内容
    params.put("planEsteTime", tvPlanEsteTime.getText().toString());//要求完成时间
    params.put("excManId", excManId);//执行人id
    params.put("excManName", excManName);//执行人
    params.put("coopManIds", coopManIds);//配合人id
    params.put("coopManNames", coopManNames);//配合人
    params.put("remark", etRemark.getText().toString());//备注
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  public VolleyResponse getResponse() {

    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        } else if (SuccessMessage.FAILURE.equalsIgnoreCase(message.getResult())) {
          ToastUtil.show(message.getMessage());
        } else {
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  public static WorkDistributeDetailFrament newInstance(WorkDistribute content,
      ProcessContent processContent) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putSerializable(EXTRA_PROCESSCONTENT, processContent);
    WorkDistributeDetailFrament fragment = new WorkDistributeDetailFrament();
    fragment.setArguments(args);
    return fragment;
  }

  @OnClick({ R.id.tv_planEsteTime, R.id.tv_executor_distribute, R.id.tv_corporator })
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_planEsteTime:
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date()), REQUETS_TIME);
        break;
      case R.id.tv_executor_distribute:
        Intent excman = new Intent(getActivity(), SearchPersonActivity.class);
        excman.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(excman, REQUETS_EXCMAN);
        break;
      case R.id.tv_corporator:
        Intent coopMan = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        coopMan.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        coopMan.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, coopManIds);
        startActivityForResult(coopMan, REQUETS_COOPMAN);
        break;
      default:
        break;
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUETS_TIME) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      @SuppressWarnings("deprecation") String dateStr =
          MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
      tvPlanEsteTime.setText(dateStr);
    }
    if (requestCode == REQUETS_EXCMAN) {
      //执行人单选
      CustomerDialog person =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      excManName = person.getName();
      excManId = person.getJobNo();
      tvExecutorDistribute.setText(excManName);
    }
    if (requestCode == REQUETS_COOPMAN) {
      //配合人多选
      coopManNames = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      coopManIds = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      tvCorporator.setText(coopManNames);
    }
    if (requestCode == REQUETS_DELETE) {
      //删除
      volleyPostDelete();
    }
  }
}
